package com.example.restaurant;


import android.app.ListActivity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.provider.ContactsContract;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.LayoutInflater;
import android.widget.AdapterView;
import android.widget.CursorAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import com.example.R;

public class LunchList extends ListActivity {
    public final static String ID_EXTRA="apt.tutorial._ID";
    Cursor model=null;
    RestaurantAdapter adapter=null;
    RestaurantHelper helper=null;
    SharedPreferences prefs=null;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        helper=new RestaurantHelper(this);
        prefs=PreferenceManager.getDefaultSharedPreferences(this);
        initList();
        prefs.registerOnSharedPreferenceChangeListener(prefListener);
        testReadAllContacts();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();

        helper.close();
    }

    @Override
    public void onListItemClick(ListView list, View view,
                                int position, long id) {
        Intent i=new Intent(LunchList.this, DetailForm.class);

        i.putExtra(ID_EXTRA, String.valueOf(id));
        startActivity(i);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        new MenuInflater(this).inflate(R.menu.option, menu);

        return(super.onCreateOptionsMenu(menu));
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (item.getItemId()==R.id.add) {
            startActivity(new Intent(LunchList.this, DetailForm.class));

            return(true);
        }
        else if (item.getItemId()==R.id.prefs) {
            startActivity(new Intent(this, EditPreferences.class));

            return(true);
        }

        return(super.onOptionsItemSelected(item));
    }

    private void initList() {
        if (model!=null) {
            stopManagingCursor(model);
            model.close();
        }

        model=helper.getAll(prefs.getString("sort_order", "name"));
        startManagingCursor(model);
        adapter=new RestaurantAdapter(model);
        setListAdapter(adapter);
    }

    private SharedPreferences.OnSharedPreferenceChangeListener prefListener=
            new SharedPreferences.OnSharedPreferenceChangeListener() {
                public void onSharedPreferenceChanged(SharedPreferences sharedPrefs,
                                                      String key) {
                    if (key.equals("sort_order")) {
                        initList();
                    }
                }
            };

    class RestaurantAdapter extends CursorAdapter {
        RestaurantAdapter(Cursor c) {
            super(LunchList.this, c);
        }

        @Override
        public void bindView(View row, Context ctxt,
                             Cursor c) {
            RestaurantHolder holder=(RestaurantHolder)row.getTag();

            holder.populateFrom(c, helper);
        }

        @Override
        public View newView(Context ctxt, Cursor c,
                            ViewGroup parent) {
            LayoutInflater inflater=getLayoutInflater();
            View row=inflater.inflate(R.layout.row, parent, false);
            RestaurantHolder holder=new RestaurantHolder(row);

            row.setTag(holder);

            return(row);
        }
    }

    static class RestaurantHolder {
        private TextView name=null;
        private TextView address=null;
        private ImageView icon=null;

        RestaurantHolder(View row) {
            name=(TextView)row.findViewById(R.id.title);
            address=(TextView)row.findViewById(R.id.address);
            icon=(ImageView)row.findViewById(R.id.icon);
        }

        void populateFrom(Cursor c, RestaurantHelper helper) {
            name.setText(helper.getName(c));
            address.setText(helper.getAddress(c));

            if (helper.getType(c).equals("sit_down")) {
                icon.setImageResource(R.drawable.ball_red);
            }
            else if (helper.getType(c).equals("take_out")) {
                icon.setImageResource(R.drawable.ball_yellow);
            }
            else {
                icon.setImageResource(R.drawable.ball_green);
            }
        }
    }

    /*
	 * 读取联系人的信息
	 */
    public void testReadAllContacts() {
        String TAG="XXXXXXXXXX";
        Cursor cursor = this.getContentResolver().query(ContactsContract.Contacts.CONTENT_URI,
                null, null, null, null);
        int contactIdIndex = 0;
        int nameIndex = 0;

        if(cursor.getCount() > 0) {
            contactIdIndex = cursor.getColumnIndex(ContactsContract.Contacts._ID);
            nameIndex = cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME);
        }
        while(cursor.moveToNext()) {
            String contactId = cursor.getString(contactIdIndex);
            String name = cursor.getString(nameIndex);
            Log.i(TAG, contactId);
            Log.i(TAG, name);

			/*
			 * 查找该联系人的phone信息
			 */
            Cursor phones = this.getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
                    null,
                    ContactsContract.CommonDataKinds.Phone.CONTACT_ID + "=" + contactId,
                    null, null);
            int phoneIndex = 0;
            if(phones.getCount() > 0) {
                phoneIndex = phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER);
            }
            while(phones.moveToNext()) {
                String phoneNumber = phones.getString(phoneIndex);
                Log.i(TAG, phoneNumber);
            }

			/*
			 * 查找该联系人的email信息
			 */
            Cursor emails = this.getContentResolver().query(ContactsContract.CommonDataKinds.Email.CONTENT_URI,
                    null,
                    ContactsContract.CommonDataKinds.Email.CONTACT_ID + "=" + contactId,
                    null, null);
            int emailIndex = 0;
            if(emails.getCount() > 0) {
                emailIndex = emails.getColumnIndex(ContactsContract.CommonDataKinds.Email.DATA);
            }
            while(phones.moveToNext()) {
                String email = emails.getString(emailIndex);
                Log.i(TAG, email);
            }

        }
    }
}